package com.jy.oms.framework.asyn.task.collector;

import com.jy.oms.framework.asyn.task.alarm.AlarmMessage;
import com.jy.oms.framework.asyn.task.alarm.AlarmMessageFacade;
import com.jy.oms.framework.asyn.task.constants.CacheConstants;
import com.jy.oms.framework.asyn.task.constants.TaskConstants;
import com.jy.oms.framework.asyn.task.constants.TaskStateEnum;
import com.jy.oms.framework.asyn.task.core.ExecutorContext;
import com.jy.oms.framework.asyn.task.core.RedissonClientProxy;
import com.jy.oms.framework.asyn.task.executor.ITaskLifecycleListener;
import com.jy.oms.framework.asyn.task.handler.ITaskHandlerManager;
import com.jy.oms.framework.asyn.task.handler.ITaskHandlerProcessor;
import com.jy.oms.framework.asyn.task.model.TaskGroup;
import com.jy.oms.framework.asyn.task.model.TaskHandlerWrapper;
import com.jy.oms.framework.asyn.task.model.TaskResultDto;
import com.jy.oms.framework.asyn.task.model.TaskWrapper;
import com.jy.oms.framework.asyn.task.queue.TaskQueueManagerProxy;
import org.apache.commons.collections4.MapUtils;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 超时任务收集器
 *
 * @author liuquan
 */
@Service
public class TimeoutTaskCollector implements ITaskHandlerProcessor, ITaskLifecycleListener {
    private static Logger logger = LoggerFactory.getLogger(TimeoutTaskCollector.class);
    private Map<String/**任务编码*/, Integer/**超时次数*/> taskTimeoutMap = new ConcurrentHashMap<>();
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    private long timeoutTaskTimeUpdator;

    @Autowired
    private ITaskHandlerManager taskHandlerManager;

    @Override
    public void processAfterTaskHandlerInitialization() {
        this.syncTimeoutTask();

        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    syncTimeoutTask();
                } catch (Throwable e) {
                    logger.error("同步超时任务报错", e);
                }
            }
        }, 1, 30, TimeUnit.SECONDS);
    }

    private void syncTimeoutTask() {
        RBucket<Long> bucket = this.getTimeoutTaskTimeBucket();
        Long updateTime = bucket.get();
        if (updateTime == null || !Objects.equals(this.timeoutTaskTimeUpdator, updateTime)) {
            if (updateTime == null) {
                updateTime = System.currentTimeMillis();
                this.updateTimeoutTaskTime(updateTime);
            }

            this.timeoutTaskTimeUpdator = updateTime;

            taskTimeoutMap.clear();
            Map<String, Integer> timeoutTaskMap = this.getAllTimeoutTask();
            if (MapUtils.isNotEmpty(timeoutTaskMap)) {
                for (Map.Entry<String, Integer> entry : timeoutTaskMap.entrySet()) {
                    taskTimeoutMap.put(entry.getKey(), entry.getValue());
                }
            }
        }
    }

    /**
     * 获取所有超时任务
     */
    public Set<String> getTimeoutTask() {
        return taskTimeoutMap.keySet();
    }

    private RBucket<Long> getTimeoutTaskTimeBucket() {
        String cacheKey = CacheConstants.genCacheKey(CacheConstants.TIMEOUT_TASK_TIME_COMPARE);
        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        RBucket<Long> bucket = redissonClient.getBucket(cacheKey);
        return bucket;
    }

    /**
     * 有新新增或删减超时任务时，更新超时任务时间，同步用
     */
    private void updateTimeoutTaskTime() {
        this.updateTimeoutTaskTime(System.currentTimeMillis());
    }

    private void updateTimeoutTaskTime(long time) {
        RBucket<Long> bucket = this.getTimeoutTaskTimeBucket();
        bucket.set(time, 60, TimeUnit.MINUTES);
    }

    /**
     * 获取所有超时任务
     */
    private Map<String/**任务编码*/, Integer/**超时次数*/> getAllTimeoutTask() {
        try {
            Map<String, Integer> map = new HashMap<>();

            Map<TaskGroup, List<TaskHandlerWrapper>> taskGroupListMap = taskHandlerManager.loadAllExecutableTaskHandler();
            for (Map.Entry<TaskGroup, List<TaskHandlerWrapper>> entry : taskGroupListMap.entrySet()) {
                for (TaskHandlerWrapper taskHandlerWrapper : entry.getValue()) {
                    RAtomicLong rAtomicLong = this.getCollectTimeoutBucket(taskHandlerWrapper.getTaskCode());
                    long num = rAtomicLong.get();
                    if(num > 0){
                        map.put(taskHandlerWrapper.getTaskCode(), (int) num);
                    }
                }
            }
            return map;
        } catch (Exception e) {
            logger.error("获取所有超时任务报错", e);
        }

        return Collections.emptyMap();
    }

    /**
     * 任务超时时，需更新任务状态；不同任务队列有不同处理
     *
     * @param taskWrapper 任务
     */
    @Override
    public void onTimeout(TaskWrapper taskWrapper) {
        //本地任务不计入超时统计
        if (ExecutorContext.isDev()) {
            return;
        }

        this.collectTimeoutTask(taskWrapper.getTaskCode());

        TaskResultDto fail = new TaskResultDto();
        fail.setTaskWrapper(taskWrapper);
        fail.setTaskState(TaskStateEnum.TIMEOUT);
        TaskQueueManagerProxy.locate(taskWrapper.getTaskCode()).finish(fail);
    }

    private RAtomicLong getCollectTimeoutBucket(String taskCode) {
        String cacheKey = CacheConstants.genCacheKey(CacheConstants.TIMEOUT_TASK_COLLECTOR, taskCode);
        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        RAtomicLong bucket = redissonClient.getAtomicLong(cacheKey);
        return bucket;
    }

    /**
     * 统计超时任务
     *
     * @param taskCode 任务编码
     */
    private void collectTimeoutTask(String taskCode) {
        try {
            RAtomicLong bucket = this.getCollectTimeoutBucket(taskCode);
            int num = (int) bucket.incrementAndGet();
            //只要超时一次，则十分钟内任务将不会再执行（有点粗暴）
            bucket.expire(10, TimeUnit.MINUTES);

            taskTimeoutMap.merge(taskCode, num, Integer::sum);

            //更新修改时间
            this.updateTimeoutTaskTime();

            if (num >= TaskConstants.DEFAULT_TASK_EXECUTE_TIMEOUT_THRESHOLD) {
                AlarmMessage alarmMessage = AlarmMessage.create()
                        .title("异步任务超时")
                        .add("任务taskCode", taskCode)
                        .add("超时次数", num);
                logger.warn(alarmMessage.toString());

                AlarmMessageFacade.getInstance().alarm(alarmMessage);
            }
        } catch (Exception e) {
            logger.error("任务超时计数统计错误.", e);
        }
    }

    /**
     * 任务执行成功，表示任务已恢复，清除超时标记（这里无需根据熔断状态考虑的太复杂）
     *
     * @param taskWrapper 任务
     */
    @Override
    public void onFinish(TaskWrapper taskWrapper) {
        String taskCode = taskWrapper.getTaskCode();
        if (taskTimeoutMap.get(taskCode) == null) {
            return;
        }

        taskTimeoutMap.remove(taskCode);

        RAtomicLong bucket = this.getCollectTimeoutBucket(taskCode);
        if (bucket.isExists()) {
            bucket.delete();
        }

        //更新修改时间
        this.updateTimeoutTaskTime();
    }

}
